package com.walterweimod.auxiliary_attributes.util;

import net.minecraft.client.resources.sounds.Sound;
import net.minecraft.world.entity.Entity;
import net.minecraftforge.common.capabilities.Capability;
import net.minecraftforge.common.util.NonNullConsumer;
import org.apache.commons.lang3.ObjectUtils;

import java.util.Objects;
import java.util.Optional;
import java.util.function.Function;

public class ModCapabilityUtils {
    private ModCapabilityUtils(){}

    public static <T, R> R getCapabilityValue(Entity entity,
                                              Capability<T> capability,
                                              Function<T, R> function,
                                              R defaultValue) {
        if (ObjectUtils.allNotNull(entity, capability, function)) {
            return entity.getCapability(capability)
                    .resolve() // 确保 Capability 存在
                    .map(function) // 如果存在，则执行转换
                    .orElse(defaultValue); // 否则返回默认值
        }

        return defaultValue;
    }

    public static<T> void setCapabilityValue(Entity entity,
                                             Capability<T> capability,
                                             NonNullConsumer<T> consumer){
        if (ObjectUtils.allNotNull(entity, capability, consumer)
                && !entity.level.isClientSide()){
            entity.getCapability(capability).ifPresent(consumer);
        }
    }
}
